#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <error.h>
#include <pthread.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

#include "tcp.h"
#include"jpg.h"


#define REQ_DATA_SIZE   32
#define HDR_DATA_SIZE   128

extern pthread_mutex_t jpg_mutex;
extern int picconfd;

int client_process(int connfd, struct jpg_buf_t *jpg)
{

	unsigned int piclen = 0;
	unsigned char * buf ;
	char response[20] = {0};
	char msg[3] = {0};
	int total = 0;
	int ret1 = 0;
	int i = 0;
	
	ret1 = read(connfd,msg,3);
	//printf("msg  :  %s\n",msg);
	
	pthread_mutex_lock(&jpg_mutex);
	piclen = jpg->len;
	//printf("piclen = %d\n",piclen);
	snprintf(response, sizeof(response), "%dlen", piclen);
	
	buf = (unsigned char *)malloc(piclen);
	memset(buf,0,piclen);
	memcpy(buf,jpg->buf,piclen);
	
	pthread_mutex_unlock(&jpg_mutex);
	
	int ret = write(connfd,response,20);
	//printf("ret = %d\n",ret);
	while(piclen>total)
	{
	    ret1 = write(connfd,buf+total,piclen-total);
	    if(ret1 < 0)
	    {
	        break;
	    }
	    total += ret1;
	   // printf("total = %d\n",total);
	    
	}
	return 0;
}


int send_screenshop(int i)
{
	int pic_fd = 0;
	int total = 0;
	char path[50] = {0};
	memset(path,0,50);
	struct stat pic_stat;
    int length = 0;
	char command[50] = {0};
	char *buf = NULL;
	buf = (char*)malloc(MAX_JPG_SIZE);
	memset(buf,0,MAX_JPG_SIZE);
	int ret = 0;
    total = 0;

	sprintf(path,"/pictrue/pictrue%d.jpg",i);
    pic_fd = open(path,O_RDONLY);
	if(pic_fd < 0)
	{
		printf("open pictrue file err\n");
		write(picconfd,"no more recard",50);
		return -1;
	}
	else
	{
		printf("open picture file success\n");
	}

	stat(path,&pic_stat);
	length = pic_stat.st_size;
	memset(command,0,50);
	sprintf(command,"%dpiclen",length);
	printf("%s\n",command);
    ret = write(picconfd,command,50);
	if(ret < 1)
	{
		printf("write length err\n");
		return -1;
	}

    
	while(total < length)
	{
	    ret = read(pic_fd,buf+total,length-total);
        if(ret < 1)
		{
			printf("read err\n");
			continue;
		}
		total = total+ret;
	}

    printf("read picture file ok\n");


	total = 0;
	ret = 0;
	while(total < length)
	{
		ret = write(picconfd,buf+total,length-total);
		if(ret < 1)
		{
			printf("send to QT err\n");
			continue;
		}
		total = total+ret;
	}
    printf("send to QT success");
	free(buf);
	return 0;
}


